<?php
class WidgetsList extends FWidget
{
    public $selected_cat_id = 0;
    public $current_page = 0;
    public $container_id = 'widgets-container';
    
    public $extra_data = array();
    
    public $for_adding_into_page = TRUE;
    
    public function run()
    {
        // get vocabulary "Widgets"
        $widget_vol = Vocabulary::model()->find("name='Widgets'");
        if (is_null($widget_vol))
            throw new CHttpException(400,Yii::t('Core','Missing type "Widgets"'));
        
        $criteria = new CDbCriteria();
        $criteria->join = '
        INNER JOIN "'.SITE_TABLE_PREFIX.'taxonomy_index" "ti" ON "t"."id" = "ti"."object_id"
        INNER JOIN "'.SITE_TABLE_PREFIX.'taxonomy_term" "tt" ON "ti"."term_id" = "tt"."id"
        ';
        $criteria->condition = "tt.v_id={$widget_vol->id} AND t.status = true";
        // if there is param cat_id
        if (!empty($this->selected_cat_id))
            $criteria->addCondition("ti.term_id={$this->selected_cat_id}");
            
        // create pager
        $criteria->select = '"t"."id"';
        $countWidget = CmsWidget::model()->count($criteria);
        $paging = new CPagination($countWidget);
        $paging->pageSize = 9;
        if ($this->current_page > 0) $this->current_page--;
        $paging->currentPage = $this->current_page;
        $paging->applyLimit($criteria);
        
        $criteria->select = '"t".*';
        $criteria->order = '"t"."creation_datetime" DESC';
        $widgets = CmsWidget::model()->findAll($criteria);
        
        $this->render('WidgetsList',array('widgets'=>$widgets,'paging'=>$paging));
    }
}